package com.wuyb.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wuyb.enums.ErrorCode;
import com.wuyb.pojo.entity.BaseResponse;
import com.wuyb.pojo.entity.ResultUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 当访问接口没有权限时，自定义返回结果
 *
 * @Author: wyb
 * @Date: 2024/01/08/19:29
 * @Description:
 */
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        BaseResponse error = ResultUtils.error(ErrorCode.NO_AUTH_ERROR.getCode(), "无权限");
        out.write(new ObjectMapper().writeValueAsString(error));
        out.flush();
        out.close();
    }
}
